﻿using System.Windows;
using System.Windows.Controls;
using theeg.GeometryWpf;
using theeg.GraphWpf.Models;

namespace theeg.GraphWpf.Views
{
    [TemplateVisualState(Name = "MouseOver", GroupName = "CommonStates")]
    [TemplateVisualState(Name = "Normal", GroupName = "CommonStates")]
    public class NodePresenter : PresenterBase
    {
        public override IHilbertTreeNode HilbertNode
        {
            get { return Data; }
        }

        public INode Data
        {
            get { return (INode)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(INode), typeof(NodePresenter), new PropertyMetadata(null, NodeDataChanged));

        public NodePresenter()
        {
            DefaultStyleKey = typeof(NodePresenter);
        }

        private static void NodeDataChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            NodePresenter vnode = (NodePresenter)sender;
            if (e.NewValue == null)
            {
                vnode.SetValue(Canvas.LeftProperty, 0);
                vnode.SetValue(Canvas.TopProperty, 0);
            }
            else
            {
                INode node = (INode)e.NewValue;
                vnode.SetValue(Canvas.LeftProperty, node.Left);
                vnode.SetValue(Canvas.TopProperty, node.Top);
            }
        }

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            if (e.Property == IsMouseOverProperty)
            {
                CoerceMouseOver(Data, IsMouseOver);
            }
        }

        private void CoerceMouseOver(INode data, bool isMouseOver)
        {
            foreach (var edge in data.IncomingEdges)
            {
                edge.IsHighlighted = isMouseOver;
            }
            foreach (var edge in data.OutgoingEdges)
            {
                edge.IsHighlighted = isMouseOver;
            }
        }
    }
}
